package com.example.nebulaspringboot.service.impl;

import com.example.nebulaspringboot.entity.Role;
import com.example.nebulaspringboot.error.BusinessException;
import com.example.nebulaspringboot.error.EmBusinessError;
import com.example.nebulaspringboot.mapper.RoleMapper;
import com.example.nebulaspringboot.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Role selectById(Integer id) throws BusinessException {
        Role role = roleMapper.selectById(id);
        if (role == null) {
            throw new BusinessException(EmBusinessError.UNKNOWN_ERROR,"角色不存在");
        }
        return role;
    }

    @Override
    public List<Role> selectRoleList(String name) {
        return roleMapper.selectRoleList(name);
    }

    @Override
    @Transactional
    public void insertSelective(Role role) throws BusinessException {
        if (role.getName() == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        Role check = roleMapper.checkName(role.getName());
        if (check == null) {
            roleMapper.insertSelective(role);
            return;
        }
        else {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"角色名已存在");
        }
    }

    @Override
    @Transactional
    public void updateRoleById(Role role) throws BusinessException {
        if (role.getName() == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        Role check = roleMapper.checkName(role.getName());
        if(check != null || check.getId() == role.getId()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"角色名已存在");
        }
        roleMapper.updateRoleById(role);
        return;
    }

    @Override
    @Transactional
    public void deleteById(Integer id) throws BusinessException {
        Role roleCheck = this.selectById(id);
        if (roleCheck != null) {
            roleMapper.deleteRole(id);
        }
        return;
    }

    @Override
    public Role checkName(String name) {
        Role role = roleMapper.checkName(name);
        if (role == null) {
            return null;
        }
        return role;
    }
}
